package com.ccit.greenlife.interceptors;

import com.ccit.greenlife.utils.JwtUtil;
import com.ccit.greenlife.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//编写拦截器(验证token，获取ThreadLocalUtil)
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired//redis提供服务的对象
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求携带的token
        String token = request.getHeader("Authorization");
        //验证token
        try {
            //token效验（1. token内容有效  2.未过期）
            //2.
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();// 获取ValueOperations对象
            String redisToken = operations.get(token);//键值相同，如果传入的token和当前键拿到的值相同，说明没有过期
            if(redisToken == null){
                //过期则抛出异常
                throw new RuntimeException();
            }
            //1.
            Map<String, Object> claims = JwtUtil.ParseToken(token);
            //将当前用户数据存入ThreadLocal
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            //效验失败，设置响应码401.不放行
            response.setStatus(401);
            return false;
        }
    }

    //放行时执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }


}
